package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.CodeUtil;
import com.wing.order.model.request.DistributionDemandPlanDetailForm;
import com.wing.order.model.request.DistributionDemandPlanForm;
import com.wing.order.model.response.InventoryAlarmDetailVO;
import com.wing.order.model.response.InventoryAlarmVO;
import com.wing.order.service.DistributionDemandPlanDetailService;
import com.wing.order.service.DistributionDemandPlanService;
import com.wing.order.service.InventoryAlarmDetailService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.order.model.entity.InventoryAlarm;
import com.wing.order.model.request.InventoryAlarmForm;
import com.wing.order.service.InventoryAlarmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Calendar;
import java.util.List;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-库存告警管理", tags = "#/order/inventoryAlarm")
@RestController("inventoryAlarmController")
@RequestMapping("order/admin/inventoryAlarm")
@RequiredArgsConstructor
@Slf4j
public class InventoryAlarmController {

    private final InventoryAlarmService inventoryAlarmService;
    @Autowired
    private DistributionDemandPlanService distributionDemandPlanService;
    @Autowired
    private DistributionDemandPlanDetailService distributionDemandPlanDetailService;
    @Autowired
    private InventoryAlarmDetailService inventoryAlarmDetailService;

    @ApiOperation(value = "查询所有库存告警", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<InventoryAlarm> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,InventoryAlarm inventoryAlarm
    ){

        Page<InventoryAlarm> pg = new Page<>(page, limit);
        QueryWrapper<InventoryAlarm> queryWrapper = new QueryWrapper<>();
        //搜索
        if(inventoryAlarm.getStatus()!=null){
            queryWrapper.eq("status",InventoryAlarm.Status.valueOf(inventoryAlarm.getStatus().toString()));
        }
        if(StringUtils.isNotBlank(inventoryAlarm.getSkuCode())){
            queryWrapper.and(qw -> qw.like("sku_code",inventoryAlarm.getSkuCode()));
        }
        if(StringUtils.isNotBlank(inventoryAlarm.getCabCode())){
            queryWrapper.and(qw -> qw.like("cab_code",inventoryAlarm.getCabCode()));
        }
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        IPage<InventoryAlarm> list = inventoryAlarmService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加库存告警", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(InventoryAlarmForm.Add.class) InventoryAlarmForm inventoryAlarmForm) {
        Calendar cal = Calendar.getInstance();
        String date = cal.get(Calendar.YEAR) + String.valueOf(cal.get(Calendar.MONTH)) + cal.get(Calendar.DATE);
        //校验
        inventoryAlarmForm.setAlarmCode("GJ".concat(date));
        InventoryAlarm inventoryAlarm = new InventoryAlarm();
        BeanUtils.copyProperties(inventoryAlarmForm,inventoryAlarm);
        if (inventoryAlarmService.saveOrUpdate(inventoryAlarm)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改库存告警", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(InventoryAlarmForm.Update.class) InventoryAlarmForm inventoryAlarmForm) {
        InventoryAlarm inventoryAlarm = inventoryAlarmService.getById(inventoryAlarmForm.getId());
        if(inventoryAlarm == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(InventoryAlarm.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(inventoryAlarmForm, inventoryAlarm, copyOptions);
        if (inventoryAlarmService.updateById(inventoryAlarm)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除库存告警", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "inventoryAlarmId", value = "库存告警id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long inventoryAlarmId) {
        if (inventoryAlarmService.removeById(inventoryAlarmId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询告警信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "库存告警id", required = true, dataType = "Long", paramType = "query")
    })
    @GetMapping("/getInventoryAlarmById")
    public JsonResult<InventoryAlarmVO> getInventoryAlarmById(Long id) {
        InventoryAlarmVO inventoryAlarmVO = inventoryAlarmService.get4appById(id);
        return JsonResult.success(inventoryAlarmVO);
    }

    @ApiOperation(value = "添加配货需求计划", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addDistributionDemandPlan")
//    public JsonResult addDistributionDemandPlan(@Validated(DistributionDemandPlanForm.Add.class) DistributionDemandPlanForm distributionDemandPlanForm,
//    @Validated(DistributionDemandPlanDetailForm.Add.class) DistributionDemandPlanDetailForm distributionDemandPlanDetailForm) {
    public JsonResult addDistributionDemandPlan(InventoryAlarmForm inventoryAlarmForm){
        /**
        InventoryAlarmDetailVO inventoryAlarmDetailVO = inventoryAlarmDetailService.get4appById(distributionDemandPlanForm.getAlarmId());
        distributionDemandPlanDetailForm.setSpaceId(inventoryAlarmDetailVO.getSpaceId());
        if (distributionDemandPlanService.add(distributionDemandPlanForm) > 0 && distributionDemandPlanDetailService.add(distributionDemandPlanDetailForm) > 0) {
            InventoryAlarm inventoryAlarm = inventoryAlarmService.getById(distributionDemandPlanForm.getAlarmId());
            if(inventoryAlarm == null){
                return JsonResult.fail("修改失败！");
            }
            inventoryAlarm.setStatus(InventoryAlarm.Status.valueOf("confirmed"));
            inventoryAlarmService.updateById(inventoryAlarm);
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");*/
        try{
            inventoryAlarmService.confirm(inventoryAlarmForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("confirm fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }
}
